package examples.generics;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;

public class GenericsExamples {

	public static <E> Set<E> removeDups(Collection<E> c) {
		return new LinkedHashSet<E>(c);
	}

	public static <E> void replace(List<E> list, E val,
			List<? extends E> newVals) {
		for (ListIterator<E> it = list.listIterator(); it.hasNext();) {
			if (val == null ? it.next() == null : val.equals(it.next())) {
				it.remove();
				for (E e : newVals)
					it.add(e);
			}
		}
	}

	static <E> List<E> heapSort(Collection<E> c) {
		Queue<E> queue = new PriorityQueue<E>(c);
		List<E> result = new ArrayList<E>();

		while (!queue.isEmpty())
			result.add(queue.remove());

		return result;
	}

	static <K, V> boolean validate(Map<K, V> attrMap, Set<K> requiredAttrs,
			Set<K> permittedAttrs) {
		boolean valid = true;
		Set<K> attrs = attrMap.keySet();

		if (!attrs.containsAll(requiredAttrs)) {
			Set<K> missing = new HashSet<K>(requiredAttrs);
			missing.removeAll(attrs);
			System.out.println("Missing attributes: " + missing);
			valid = false;
		}
		if (!permittedAttrs.containsAll(attrs)) {
			Set<K> illegal = new HashSet<K>(attrs);
			illegal.removeAll(permittedAttrs);
			System.out.println("Illegal attributes: " + illegal);
			valid = false;
		}
		return valid;
	}

}
